package netbayServlet;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.StringTokenizer;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import util.String.StringUtil;
import util.jQgrid.JQGridFormatterUtil;

import netbay.FileDao;
import netbay.NetbayUtility;
import netbay.SFTPManager;
import netbay.TransactionLog;
import netbay.TransactionManager;
import netbay.UserManager;
import netbay.Worker;
import netbay.WorkerManager;

/**
 * Servlet implementation class ResendFileServlet
 */
public class ResendFileServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public ResendFileServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	public void init() {

		String configPath = getServletContext().getRealPath(
				"/WEB-INF/config.properties");
		
			NetbayUtility.init(configPath);
		
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/json;charset=utf-8");
		HttpSession session = request.getSession();
		String url = "";
		String converId = ((!StringUtil.isNullOrEmpty((String) (request
				.getParameter("converId")))) ? (String) request
				.getParameter("converId") : "null");
		String type = ((!StringUtil.isNullOrEmpty((String) (request
				.getParameter("type")))) ? (String) request
				.getParameter("type") : "null");
		request.setAttribute("typeShort", type);
		if (type.equals("reTCDTCD"))
			type = "Resend file to TCD";
		if (type.equals("reJPMCTCD") || type.equals("reJPMCRD"))
			type = "Resend file to JPMC";
		if (type.equals("reRDRD"))
			type = "Resend file to RD";
		request.setAttribute("converId", converId);
		request.setAttribute("type", type);

		String userId = ((!StringUtil.isNullOrEmpty((String) (session
				.getAttribute("userId")))) ? (String) session
				.getAttribute("userId") : "null");
		if (!(userId.equals("null"))) {
			url = "/ResendFile.jsp";
		} else {
			url = "/Login.jsp";
		}

		try {
			request.getRequestDispatcher(url).forward(request, response);
		} catch (Exception ex) {
			ex.printStackTrace();
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
		HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/json;charset=utf-8");
		String userPath = request.getServletPath();
		PrintWriter out = response.getWriter();
		String strJson = "{}";
		TransactionManager tm = new TransactionManager();
		if (userPath.equals("/" + "ResendFileServlet/Resend")) {
			String converId = ((!StringUtil.isNullOrEmpty((String) (request
					.getParameter("converId")))) ? (String) request
					.getParameter("converId") : "null");
			String type = ((!StringUtil.isNullOrEmpty((String) (request
					.getParameter("type")))) ? (String) request
					.getParameter("type") : "null");

			String page = request.getParameter("page"); // get the requested
			// page
			String limit = request.getParameter("rows"); // get how many rows we
			// want to have into
			// the grid
			String sidx = request.getParameter("sidx"); // get index row - i.e.
			// user click to sort
			String sord = request.getParameter("sord"); // get the direction

			String data[] ;
			if (type.equals("reJPMCTCD")) {
				try {
					FileDao fileMng = new FileDao();
					String TCDStorePath = WorkerManager.TCDRecvDir;
					File expFolder = new File(TCDStorePath);
					//String[] fileList = fileMng.exploreFolder(expFolder);
					
					//List<String> xmlList = new ArrayList<String>();
					List<String[]> xmlList = new ArrayList<String[]>();
					
					File[] fileList = fileMng.exploreFolder(expFolder,"2");
					

					
					if (fileList.length == 0){
						strJson = "{\"error\": \"Don't have file\"}" ;
					}else {
						for (int i = 0; i < fileList.length; ++i) {
							if (fileList[i].getName().length() > 6) {
								String fileName = fileList[i].getName();
	
								if (fileName.substring(fileName.length() - 4,
										fileName.length()).equalsIgnoreCase(".xml")) {
									String[] cut = fileName.split("[_\\-.]");
									if (cut[2].equals(converId)) {
										data = new String[2];
										data[0] = fileName;
										Double sizes  = Math.ceil((double)fileList[i].length()/1000);
										data[1] = Double.toString(sizes);
										xmlList.add(data);
									}
								}
							}
						}
						List result = null;
						Integer all = 0;
				
						Collections.sort(xmlList,new MyComparable());
						
						result = tm.getDisplayResendTCD(xmlList, "jpmc", page, limit,
								sidx, sord);
						all = result.size();
						
						strJson = JQGridFormatterUtil.getJSON(Integer.parseInt(page), Integer.parseInt(limit), all,result);
						//out.println(strJson);
					}
				} catch (Exception ex) {
					strJson = "{\"error\": \"" + ex.getMessage() + "\"}" ;
				}
				
				//out.println(strJson);
			} else if (type.equals("reTCDTCD")) {
				try {
					SFTPManager manager = new SFTPManager();
					List<String[]> fileList = null;
					fileList = manager.lsForFilesFile();
					
					List<String[]> xmlList = new ArrayList<String[]>();
					
					
					if (fileList == null || fileList.size() == 0) {
						 //System.out.println("None of files");
						strJson = "{\"error\": \"Don't have file\"}" ;

					} else {
						for (int i = 0; i < fileList.size(); ++i) {
							String fileName = fileList.get(i)[0];

							if (fileName.length() > 5) {
								if (fileName.substring(fileName.length() - 4,
										fileName.length()).equalsIgnoreCase(
										".xml")) {
									String[] cut = fileName.split("[--.]");
									if (cut.length > 2) {
										if (cut[1].equals(converId)) {
											data = new String[2];
											data[0] = fileName;
											data[1] = fileList.get(i)[1];
											xmlList.add(data);
										}
									}

								}
							}
						}
						List result = null;
						Integer all = 0;

						Collections.sort(xmlList,new MyComparable());
						result = tm.getDisplayResendTCD(xmlList, "tcd", page,
								limit, sidx, sord);
						all = result.size();

						strJson = JQGridFormatterUtil.getJSON(Integer.parseInt(page), Integer.parseInt(limit), all,
								result);
						//out.println(strJson);
					}
					
				} catch (Exception ex) {
					strJson = "{\"error\": \"" + ex.getMessage() + "\"}" ;
					//out.println(strJson);
				}
			}else if(type.equals("reRDRD")){
				try {
					SFTPManager manager = new SFTPManager();
					List<String[]> fileList = null;
					fileList = manager.lsForFilesFile();
					
					List<String[]> xmlList = new ArrayList<String[]>();
					
					
					if (fileList == null || fileList.size() == 0) {
						 //System.out.println("None of files");
						strJson = "{\"error\": \"Don't have file\"}" ;

					} else {
						for (int i = 0; i < fileList.size(); ++i) {
							String fileName = fileList.get(i)[0];

							if (fileName.length() > 5) {
								if (fileName.substring(fileName.length() - 4,
										fileName.length()).equalsIgnoreCase(
										".xml")) {
									String[] cut = fileName.split("[--.]");
									if (cut.length > 2) {
										if (cut[1].equals(converId)) {
											data = new String[2];
											data[0] = fileName;
											data[1] = fileList.get(i)[1];
											xmlList.add(data);
										}
									}

								}
							}
						}
						List result = null;
						Integer all = 0;

						Collections.sort(xmlList,new MyComparable());
						result = tm.getDisplayResendTCD(xmlList, "rd", page,
								limit, sidx, sord);
						all = result.size();

						strJson = JQGridFormatterUtil.getJSON(Integer.parseInt(page), Integer.parseInt(limit), all,
								result);
						//out.println(strJson);
					}
					
				} catch (Exception ex) {
					strJson = "{\"error\": \"" + ex.getMessage() + "\"}" ;
					//out.println(strJson);
				}
			}else if(type.equals("reJPMCRD")){
				try {
					FileDao fileMng = new FileDao();
					String TCDStorePath = WorkerManager.TCDRecvDir;
					File expFolder = new File(TCDStorePath);
					//String[] fileList = fileMng.exploreFolder(expFolder);
					
					//List<String> xmlList = new ArrayList<String>();
					List<String[]> xmlList = new ArrayList<String[]>();
					
					File[] fileList = fileMng.exploreFolder(expFolder,"2");
					

					
					if (fileList.length == 0){
						strJson = "{\"error\": \"Don't have file\"}" ;
					}else {
						for (int i = 0; i < fileList.length; ++i) {
							if (fileList[i].getName().length() > 6) {
								String fileName = fileList[i].getName();
	
								if (fileName.substring(fileName.length() - 4,
										fileName.length()).equalsIgnoreCase(".xml")) {
									String[] cut = fileName.split("[-\\-.]");
									if (cut[1].equals(converId)) {
										data = new String[2];
										data[0] = fileName;
										Double sizes  = Math.ceil((double)fileList[i].length()/1000);
										data[1] = Double.toString(sizes);
										xmlList.add(data);
									}
								}
							}
						}
						List result = null;
						Integer all = 0;
				
						Collections.sort(xmlList,new MyComparable());
						
						result = tm.getDisplayResendTCD(xmlList, "jpmcrd", page, limit,
								sidx, sord);
						all = result.size();
						
						strJson = JQGridFormatterUtil.getJSON(Integer.parseInt(page), Integer.parseInt(limit), all,result);
						//out.println(strJson);
					}
				} catch (Exception ex) {
					strJson = "{\"error\": \"" + ex.getMessage() + "\"}" ;
				}
				
				//out.println(strJson);
			}
			out.println(strJson);
		}
	}
	
	public class MyComparable implements Comparator<String[]>{
		@Override
		public int compare(String[] o1, String[] o2) {
			// TODO Auto-generated method stub
			return ((o1[0].compareTo(o2[0].toString())>00) ? -1 : ((o1[0].toString().compareTo(o2[0].toString())==0 ? 0 : 1)));
		}
	}
	
}
